﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Weber.CS3280.Inventory.Logic;
using Weber.CS3280.Inventory.UI.Controls;
using Weber.CS3280.Inventory.UI.Windows;
using Weber.CS3280.UI.ViewModels;

namespace Weber.CS3280.Inventory.UI.ViewModels
{
	public class ItemCategoryListViewModel : ListingViewModelBase
	{
		private ItemCategoryViewModel[] _itemCategories;

		public ItemCategoryListViewModel()
		{
			Lookstone.Data.DataEvent.AddChangeEventHandler(OnDataChanged);
			WindowTitle = "Item Category Listing";
		}

		private void OnDataChanged(object sender, Lookstone.Data.DataEvent.DataChangeEventArgs e)
		{
			// Watch for ItemCategory records getting changed
			if (e.EventObject is Data.ItemCategory)
			{
				// Refresh the categories
				RefreshView();
			}
		}

		private void ReloadCategories()
		{
			using (Data.InventoryConnectionContext context = new Data.InventoryConnectionContext())
			{
				_itemCategories = ItemCategoryController.GetCategories(context)
					.Select(ic => new ItemCategoryViewModel(ic))
					.ToArray();
			}
		}

		protected override void AddItem(System.Windows.Controls.Control control)
		{
			EditControlHostWindow.ShowWindow<ItemCategoryDetailsControl>(new ItemCategoryViewModel(), Window.GetWindow(control));
		}

		protected override ViewModelBase[] GetItems()
		{
			ReloadCategories();

			return _itemCategories;
		}

		public string GetCategoryName(int itemCategoryId)
		{
			ItemCategoryViewModel category = _itemCategories.FirstOrDefault(cat => cat.ItemCategoryId == itemCategoryId);

			if (category == null)
				return string.Empty;

			return category.Name;
		}
	}
}
